import { assign } from 'lodash';
import { AnyAction } from 'redux';
import ACTIONS from 'constants/tag';
import { arrayRemoveItem } from 'utils/utils';

const initialState: Record<string, any> = {
  tagTotal: 0,
  tagList: [],
  selectedTags: [],
};
let selectedTags = [];

export default (state = initialState, action: AnyAction) => {
  switch (action.type) {
    case ACTIONS.FETCH_LIST_SUCCESS:
      return assign({}, state, {
        tagList: action.response.data.items,
        tagTotal: action.response.data.total,
      });

    case ACTIONS.TOGGLE_CHECK:
      selectedTags = state.selectedTags;
      if (action.checked) {
        if (action.max === 0 || selectedTags.length < action.max) {
          selectedTags = [action.tag, ...selectedTags];
        }
      } else {
        selectedTags = arrayRemoveItem(selectedTags, action.tag);
      }

      // state对对象类型的引用，其对象内部改变不会导致state变化
      // 也就不会触发UI重绘，故这里要返回一个新的数组引用
      return assign({}, state, {
        selectedTags: selectedTags.slice(),
      });

    case ACTIONS.INIT_SELECTED_ITEM:
      return assign({}, state, {
        selectedTags: action.ownItems,
      });

    default:
      return state;
  }
};
